/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.commons.transaction.Impl;

import io.iec.edp.caf.commons.transaction.JpaTransaction;
import io.iec.edp.caf.commons.transaction.TransactionPropagation;
import io.iec.edp.caf.commons.transaction.entity.EcpDBTransactionWarning;
import io.iec.edp.caf.commons.transaction.repository.EcpDBTransactionWarningRepository;
import io.iec.edp.caf.commons.transaction.service.DBTransactionService;
import io.iec.edp.caf.tenancy.api.context.MultiTenantContextInfo;
import io.iec.edp.caf.tenancy.core.context.MultiTenantContextHolder;
import lombok.extern.slf4j.Slf4j;

import java.time.OffsetDateTime;

/**
 * 未提交事务外部调用接口实现
 *
 * @author manwenxing01
 */
@Slf4j
public class DBTransactionServiceImpl implements DBTransactionService {

    //持久层
    private EcpDBTransactionWarningRepository repo;

    //构造注入
    public DBTransactionServiceImpl(EcpDBTransactionWarningRepository repo) {
        this.repo = repo;
    }

    @Override
    public void save(String path, String message, OffsetDateTime time, String type) {
        EcpDBTransactionWarning entity = new EcpDBTransactionWarning(path, message, time, type);
        if (entity.notEmpty()) {
            try {
                //直接注册到主库
                MultiTenantContextInfo contextInfo = new MultiTenantContextInfo();
                contextInfo.setMasterDb(true);
                MultiTenantContextHolder.set(contextInfo);

                //新开事务保存
                JpaTransaction transaction = JpaTransaction.getTransaction();
                try {
                    transaction.begin(TransactionPropagation.REQUIRES_NEW);
                    repo.save(entity);
                    transaction.commit();
                } catch (Throwable e) {
                    transaction.rollback();
                    log.error("An exception occurred while logging an uncommitted transaction. Current path:{}", entity.getPath(), e);
                }
                log.error("There is an uncommitted transaction. Current path:{},type:{}", entity.getPath(), entity.getType());
            } finally {
                MultiTenantContextHolder.set(null);
            }
        }
    }
}
